package com.lw.leetcode.str.a;

import java.util.Arrays;

/**
 * 409. 最长回文串
 * 5. 最长回文子串
 *
 * @Author liw
 * @Date 2021/5/8 14:39
 * @Version 1.0
 */
public class LongestPalindrome {

    public int longestPalindrome(String s) {
        int length = s.length();
        if (length < 2) {
            return length;
        }
        int[] arr = new int[128];

        for (int i = 0; i < length; i++) {
            arr[s.charAt(i)] += 1;
        }
        int max = 0;
        boolean flag = false;
        for (int i = 0; i < 128; i++) {
            int value = arr[i];
            if (value != 0) {
                max += value;
                if ((value & 1) != 0) {
                    max--;
                    flag = true;
                }
            }
        }
        return flag ? max + 1 : max;
    }

    public String longestPalindrome2(String s) {
        if (s == null) {
            return null;
        }
        int length = s.length();
        if (length < 2) {
            return s;
        }
        String returnStr = s.substring(0, 1);
        int maxLength = 1;
        byte[] bytes = s.getBytes();
        for (int i = 1; i < length; i++) {
            String aa = aa(bytes, i, i, maxLength);
//            System.out.println("**** " + aa);
            if (aa != null) {
                maxLength = aa.length();
                returnStr = aa;
            }
            aa = aa(bytes, i - 1, i, maxLength);
            if (aa != null) {
                maxLength = aa.length();
                returnStr = aa;
            }
        }
        return returnStr;


    }


    public String aa(byte[] bytes, int st, int end, int maxLength) {
        int up = bytes.length - 1;
        int d = 0;


        while (st >= d && end <= up && bytes[st] == bytes[end]) {
            st--;
            end++;
        }

        st++;
        end--;
        if (end - st + 1 > maxLength) {
            return new String(Arrays.copyOfRange(bytes, st, end + 1));
        } else {
            return null;
        }
    }

}
